﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.ExpressApp.Win.Editors;
using DevExpress.ExpressApp.Editors;
using DevExpress.ExpressApp.Model;
using System.ComponentModel;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using System.Runtime.CompilerServices;

namespace SpeedSCM.Module.Win
{
    [PropertyEditor(typeof(Object), false)]
    public class WinStringArrayComboPropertyEditor : WinPropertyEditor
    {
        // Fields
        private readonly string dataSourceProperty;

        // Methods
        public WinStringArrayComboPropertyEditor(Type objectType, IModelMemberViewItem info)
            : base(objectType, info)
        {
            //this.dataSourceProperty = string.Empty;
            this.ControlBindingProperty = "EditValue";
            this.dataSourceProperty = info.DataSourceProperty;
        }

        private void combo_QueryPopup(object sender, CancelEventArgs e)
        {
            this.UpdateComboValues();
        }
        protected override object CreateControlCore()
        {
            ComboBoxEdit combo = new ComboBoxEdit();
            //combo.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
            combo.Properties.QueryPopUp += new CancelEventHandler(this.combo_QueryPopup);
            return combo;
        }

        protected override void Dispose(bool disposing)
        {
            ComboBoxEdit combo = this.Control as ComboBoxEdit;
            if (combo != null)
            {
                combo.Properties.QueryPopUp -= new CancelEventHandler(this.combo_QueryPopup);
            }
            base.Dispose(disposing);
        }

        protected override void OnControlCreated()
        {
            this.UpdateComboValues();
            base.OnControlCreated();
        }

        private void UpdateComboValues()
        {
            if (this.CurrentObject != null)
            {
                ComboBoxEdit combo = (ComboBoxEdit)this.Control;
                combo.Properties.Items.Clear();
                if (this.CurrentObject != null)
                {
                    Type t = this.CurrentObject.GetType();
                    if (t.GetProperty(this.dataSourceProperty) != null)
                    {
                        string[] values = (string[])t.GetProperty(this.dataSourceProperty).GetValue(RuntimeHelpers.GetObjectValue(this.CurrentObject), null);
                        if (values != null)
                        {
                            combo.Properties.Items.AddRange(values);
                        }
                    }
                }
            }
        }
    }

 

}
